#coding=utf-8
'''
2.5. Searching and Replacing Text
replace(), sub()
'''
text = 'yeah, but no, but yeah, but no, but yeah'
a = text.replace('yeah', 'yep')
print(text)
print(a)

text2 = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
import re
b = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text2)
print(b)

import re
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
c = datepat.sub(r'\3-\1-\2', text2)
print(c)

# For more complicated substitutions, it’s possible to specify a substitution callback function instead
from calendar import month_abbr
def change_date(m):
    mon_name = month_abbr[int(m.group(1))]
    return '{} {} {}'.format(m.group(2), mon_name, m.group(3))  # 日、月、年
d = datepat.sub(change_date, text2)
print(d)

# re.subn()：If you want to know how many substitutions were made in addition to getting the replacement text
newtext = datepat.subn(r'\3-\1-\2', text)
print(newtext)